package com.weiyi.chat.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.weiyi.chat.R;
import com.weiyi.chat.api.IUserList;
import com.weiyi.chat.common.Constant;
import com.weiyi.chat.common.base.BaseFragment;
import com.weiyi.chat.common.base.MyBaseAdapter;
import com.weiyi.chat.domain.UserList;
import com.weiyi.chat.presenter.UserListPresenter;
import com.weiyi.chat.transformer.GlideCircleTransformer;
import com.weiyi.chat.ui.activity.GroupSendMsgActivity;
import com.weiyi.chat.ui.activity.SystemMsgActivity;
import com.weiyi.chat.ui.activity.UserProfileActivity;
import com.weiyi.chat.utils.MyReusouce;
import com.weiyi.chat.utils.PreferenceUtil;
import com.weiyi.chat.utils.ToastUtil;
import com.weiyi.chat.view.SideLetterBar;
import com.weiyi.chat.view.widget.ContactItemView;
import com.weiyi.chat.view.widget.HeadLayout;

import butterknife.BindView;
import butterknife.Unbinder;

import static com.baidu.location.f.mC;

/**
 * Created by Lee on 2017/8/22 0022.
 */
public class MessageFragment extends BaseFragment implements IUserList.Views {
    @BindView(R.id.hl_head)
    HeadLayout mHlHead;
    @BindView(R.id.listview_all_contacts)
    ListView mListview;
    @BindView(R.id.tv_letter_overlay)
    TextView mTvLetterOverlay;
    @BindView(R.id.side_letter_bar)
    SideLetterBar mSideLetterBar;
    Unbinder unbinder;
    private UserListPresenter mUserListPresenter;
    private MyBaseAdapter<UserList.BodyBean.DataBean> mAdapter;
    private ContactItemView mSystemItem;
    private ContactItemView mAdminItem;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_main_msg;
    }

    @Override
    public void initViews() {
        mHlHead.setBackVisibility(false);
        mHlHead.setTitle("通讯录");
        mUserListPresenter = new UserListPresenter(mContext, this);
        @SuppressLint("InflateParams")
        View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.message_header, null);
        HeaderItemClickListener clickListener = new HeaderItemClickListener();
        mSystemItem = (ContactItemView) headerView.findViewById(R.id.system_item);
        mAdminItem = (ContactItemView) headerView.findViewById(R.id.admin_item);
        mSystemItem.setOnClickListener(clickListener);
        mAdminItem.setOnClickListener(clickListener);

        mListview.addHeaderView(headerView);

//        mSideLetterBar.setOverlay(mTvLetterOverlay);
//        mSideLetterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
//            @Override
//            public void onLetterChanged(String letter) {
//                int position = mAdapter.getLetterPosition(letter);
//                mListview.setSelection(position);
//            }
//        });

        mAdapter = new MyBaseAdapter<UserList.BodyBean.DataBean>(new MyBaseAdapter.initView<UserList.BodyBean.DataBean>() {
            @Override
            public View initItenView(int position, View convertView, ViewGroup parent, UserList.BodyBean.DataBean obj) {
                ViewHolder holder;
                if (convertView == null) {
                    convertView = LayoutInflater.from(mContext).inflate(R.layout.ease_row_contact, null);
                    holder = new ViewHolder();
                    holder.avatar = (ImageView) convertView.findViewById(com.hyphenate.easeui.R.id.avatar);
                    holder.nameView = (TextView) convertView.findViewById(com.hyphenate.easeui.R.id.name);
                    holder.headerView = (TextView) convertView.findViewById(com.hyphenate.easeui.R.id.header);
                    convertView.setTag(holder);
                }
                holder = (ViewHolder) convertView.getTag();
                holder.nameView.setText(obj.getBus_owner());
                Glide.with(mContext)
                    .load(MyReusouce.BASE_URL + obj.getInfo_avatar_origin())
                    .diskCacheStrategy(DiskCacheStrategy.RESULT)
                    .transform(new GlideCircleTransformer(mContext))
                    .placeholder(com.hyphenate.easeui.R.drawable.ease_default_avatar)
                    .into(holder.avatar);

                return convertView;
            }
        });
        mListview.setAdapter(mAdapter);
        mListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                startActivity(new Intent(mContext, UserProfileActivity.class)
                        .putExtra("username", ((UserList.BodyBean.DataBean)parent.getAdapter().getItem(position)).getBus_mobile())
                        .putExtra("setting", false)
                        .putExtra("uid", ((UserList.BodyBean.DataBean)parent.getAdapter().getItem(position)).getBus_id())
                        .putExtra("usernick", ((UserList.BodyBean.DataBean)parent.getAdapter().getItem(position)).getBus_owner()));
            }
        });
    }

    @Override
    public void initLoadData() {
        if (PreferenceUtil.getValueB(Constant.SP_ISADMIN, false, mContext)){
            mHlHead.setRightText("群发");
            mHlHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(mContext, GroupSendMsgActivity.class));
                }
            });
            mUserListPresenter.requestAllUserList();
        }else{
            mHlHead.setRightTextVisibility(false);
            mUserListPresenter.requestAdminList();
        }
    }

    @Override
    public void onResetAdminSucess(UserList.BodyBean body) {
        mAdapter.setList(body.getData());
    }

    @Override
    public void onResetUserSucess(UserList.BodyBean body) {
        mAdapter.setList(body.getData());
    }

    @Override
    public void showError(String msg) {
        ToastUtil.showTextToast(mContext, msg);
        if (Constant.TOKEN_FIAL.equals(msg)){
            ToastUtil.showTextToast(mContext, "请重新登录");
            PreferenceUtil.clearAll(mContext);
            mContext.toLogin();
        }
    }

//    public class CityListAdapter extends BaseAdapter {
//        private static final int VIEW_TYPE_COUNT = 3;
//
//        private Context mContext;
//        private LayoutInflater inflater;
//        private List<ContactsModel> mContacts;
//        private HashMap<String, Integer> letterIndexes;
//        private String[] sections;
//
//
//        public CityListAdapter(Context mContext, List<ContactsModel> contacts) {
//            this.mContext = mContext;
//            this.mContacts = contacts;
//            this.inflater = LayoutInflater.from(mContext);
//            if (mContacts == null){
//                mContacts = new ArrayList<>();
//            }
//            int size = mContacts.size();
//            letterIndexes = new HashMap<>();
//            sections = new String[size];
//            for (int index = 0; index < size; index++){
//                String phonebook_label = mContacts.get(index).getPhonebook_label();
//                letterIndexes.put(phonebook_label, index);
//                sections[index] = phonebook_label;
//            }
//        }
//
//        /**
//         * 获取字母索引的位置
//         * @param letter
//         * @return
//         */
//        public int getLetterPosition(String letter){
//            Integer integer = letterIndexes.get(letter);
//            return integer == null ? -1 : integer;
//        }
//
//        @Override
//        public int getViewTypeCount() {
//            return VIEW_TYPE_COUNT;
//        }
//
//        @Override
//        public int getItemViewType(int position) {
//            return position < VIEW_TYPE_COUNT - 1 ? position : VIEW_TYPE_COUNT - 1;
//        }
//
//        @Override
//        public int getCount() {
//            return mContacts == null ? 0: mContacts.size();
//        }
//
//        @Override
//        public ContactsModel getItem(int position) {
//            return mContacts == null ? null : mContacts.get(position);
//        }
//
//        @Override
//        public long getItemId(int position) {
//            return position;
//        }
//
//        @Override
//        public View getView(final int position, View view, ViewGroup parent) {
//            ViewHolder holder;
//            //所有
//            if (view == null){
//                view = inflater.inflate(R.layout.ease_row_contact, parent, false);
//                holder = new ViewHolder();
//                holder.avatar = (ImageView) view.findViewById(com.hyphenate.easeui.R.id.avatar);
//                holder.nameView = (TextView) view.findViewById(com.hyphenate.easeui.R.id.name);
//                holder.headerView = (TextView) view.findViewById(com.hyphenate.easeui.R.id.header);
//                view.setTag(holder);
//            }
//            holder = (ViewHolder) view.getTag();
//            final String name = mContacts.get(position).getName();
//
//            String currentLetter = PinyinUtils.getFirstLetter(mContacts.get(position).getPhonebook_label());
//            String previousLetter = position >= 1 ? PinyinUtils.getFirstLetter(mContacts.get(position - 1).getPhonebook_label()) : "";
//            if (!TextUtils.equals(currentLetter, previousLetter)){
//                holder.headerView.setVisibility(View.VISIBLE);
//                holder.headerView.setText(currentLetter);
//            }else{
//                holder.headerView.setVisibility(View.GONE);
//            }
//
//            holder.nameView.setText(name);
//
//            Glide.with(mContext)
//                    .load("http://bimg.tubaba.com.cn/http://img3.imgtn.bdimg.com/it/u=1961347126,526248305&fm=23&gp=0.jpg")
//                    .diskCacheStrategy(DiskCacheStrategy.RESULT)
//                    .transform(new GlideCircleTransformer(mContext))
//                    .into(holder.avatar);
//            return view;
//        }
//    }
//
    protected class HeaderItemClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.system_item:
//                    mUserListPresenter.requestAdminList();
                    startActivity(new Intent(mContext, SystemMsgActivity.class));
//                    if ((boolean) SPUtils.get(mContext, Constant.SP_ISADMIN, false)){
//                        mUserListPresenter.requestAdminList();
//                    }else{
//                        mUserListPresenter.requestAllUserList();
//                    }
                    break;
                case R.id.admin_item:
                    mUserListPresenter.requestAllUserList();
                    break;

            }
        }

    }

    private class ViewHolder {

        public ImageView avatar;
        public TextView nameView;
        public TextView headerView;
    }
}
